package com.zyx.javademo.nio.channel;

import org.junit.Test;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * @author Yaxi.Zhang
 * @since 2021/9/17 15:01
 */
public class DatagramChannelDemo {

    /**
     * 发送的实现
     */
    @Test
    public void sendDatagram() throws Exception {

        // 打开 DatagramChannel
        DatagramChannel sendChannel = DatagramChannel.open();
        InetSocketAddress sendAddress =
                new InetSocketAddress("127.0.0.1", 9999);

        // 发送
        while (true) {
            ByteBuffer buffer = ByteBuffer.wrap("send message".getBytes(StandardCharsets.UTF_8));
            sendChannel.send(buffer, sendAddress);
            System.out.println("已经完成发送:" + new Date());
            Thread.sleep(10000);
        }

    }

    /**
     * 接收的实现
     */
    @Test
    public void receiveDatagram() throws Exception {

        // 打开DatagramChannel
        DatagramChannel receiveChannel = DatagramChannel.open();
        InetSocketAddress receiveAddress = new InetSocketAddress(9999);

        // 绑定
        receiveChannel.bind(receiveAddress);

        // buffer
        ByteBuffer receiveBuffer = ByteBuffer.allocate(1024);

        // 接收
        while (true) {
            receiveBuffer.clear();

            SocketAddress socketAddress = receiveChannel.receive(receiveBuffer);

            receiveBuffer.flip();

            System.out.println(socketAddress.toString() + new Date());

            System.out.println(StandardCharsets.UTF_8.decode(receiveBuffer));
        }
    }

    /**
     * 连接read 和 write
     */
    @Test
    public void testConnect() throws Exception {

        DatagramChannel connChannel = DatagramChannel.open();

        /*connChannel.socket().bind(new InetSocketAddress(9998));*/

        connChannel.bind(new InetSocketAddress(9998));

        connChannel.connect(new InetSocketAddress("127.0.0.1", 9998));

        ByteBuffer readBuffer = ByteBuffer.allocate(512);

        while (true) {

            connChannel.write(ByteBuffer.wrap("send messeage".getBytes(StandardCharsets.UTF_8)));

            readBuffer.clear();
            connChannel.read(readBuffer);
            readBuffer.flip();

            System.out.println("ready:" + new Date());

            System.out.println("receive the message: " + StandardCharsets.UTF_8.decode(readBuffer));

            Thread.sleep(3000);

        }

    }

}
